package gatperdut.chato.core.interpreter.actions;

import gatperdut.chato.constants.CSConstantsCommandResult.CommandExecutionResult;
import gatperdut.chato.core.characters.BaseController;
import gatperdut.chato.core.interpreter.actions.generic.Action;
import gatperdut.chato.core.interpreter.grammar.comminfo.GoInfo;
import gatperdut.chato.core.room.DoorController;
import gatperdut.chato.core.room.RoomController;

public class DirectionAction extends Action {

    public DirectionAction( GoInfo info, BaseController entityController ) {
        super( info, entityController );
    }

    @Override
    public CommandExecutionResult perform() {

        if ( emptyEmote() ) {
            getEntityController().tx( "Empty emotes are not allowed." );
            return CommandExecutionResult.OK;
        }

        String emote = getLastPartEmote();
        if ( emote == null ) {
            getEntityController().tx( "Check your emote." );
            return CommandExecutionResult.OK;
        }

        if ( getEntityController().getCombatController().isInCombat() ) {
            getEntityController().tx( "You cannot walk away from combat. Use FLEE to escape." );
            return CommandExecutionResult.OK;
        }

        checkForRunningCraft();

        DoorController nextRoomDoorController = getEntityController().getRoomController().getExitsController().getAdjacentDoorController( getInfo().getDirection() );
        if ( nextRoomDoorController != null ) {
            if ( !nextRoomDoorController.getDoor().isOpen() ) {
                getEntityController().tx( nextRoomDoorController.getDoor().getDesc() + " is closed." );
                return CommandExecutionResult.OK;
            }
        }

        RoomController nextRoomController = getEntityController().getRoomController().getExitsController().getAdjacentRoomController( getInfo().getDirection() );

        if ( nextRoomController != null ) {
            RoomController previousRoom = getEntityController().getRoomController();
            getEntityController().getRoomController().getCharactersController().leaveRoom( getEntityController() );
            nextRoomController.getCharactersController().enterRoom( getEntityController() );
            getEntityController().enterRoom( nextRoomController );

            getEntityController().getEchoes().txMovement( getInfo().getDirection(), previousRoom, nextRoomController, emote );

            getEntityController().tx( getEntityController().getRoomController().show( getEntityController() ) );
        }
        else {
            getEntityController().tx( "You cannot walk in that direction." );
        }

        return CommandExecutionResult.OK;
    }

    @Override
    public boolean interruptsCrafting() {
        return true;
    }

    @Override
    public GoInfo getInfo() {
        return (GoInfo) super.getInfo();
    }
}
